const db = wx.cloud.database()
const app = getApp()

Page({
  data: {
    openid: '',
    isLoading: true,
    user: {
      _id: '',
      name: ''
    },
    baby: [],
    showForm: '',
    formTab: ''
  },
  getOpenid: function () {
    let that = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.cloud.callFunction({
      name: 'login',
      data: {}
    }).then(res => {
      let openid = res.result.openid
      wx.hideLoading()
      that.setData({
        isLoading: false,
        openid: openid
      }, () => {
        that.loadBaby()
      })
      wx.setStorage({
        key: 'openid',
        data: openid
      })
      db.collection('users').doc(openid).get({
        success: res => {
          that.setData({
            user: res.data
          })
        }
      })
    }).catch(err => {
      wx.hideLoading()
      that.setData({
        isLoading: false
      })
      wx.showToast({
        title: '登录失败',
        icon: 'none'
      })
    })
  },
  loadBaby: function () {
    let that = this,
      data = that.data,
      openid = data.openid
    wx.cloud.callFunction({
      name: 'dbLookup',
      data: {
        db_name: 'user_baby',
        lookup: {
          from: 'baby',
          localField: 'baby_id',
          foreignField: '_id',
          as: 'info'
        },
        match: {
          _openid: openid,
          deled: false,
          'info.deled': false
        },
        sort: {
          create_time: -1
        }
      }
    }).then(res => {
      that.setData({
        baby: res.result.list
      })
    })
  },
  babyTap: function (e) {
    let that = this,
      id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/baby/baby?id=' + id
    })
  },
  addTap: function () {
    let that = this
    that.setData({
      showForm: 'baby',
      formTab: 'add'
    })
  },
  xTap: function () {
    let that = this
    that.setData({
      showForm: '',
      formTab: ''
    })
  },
  tabTap: function (e) {
    let that = this,
      tab = e.currentTarget.dataset.tab
    that.setData({
      formTab: tab
    })
  },
  addSubmit: function (e) {
    let that = this,
      name = e.detail.value.name
    if (name.length == 0) {
      wx.showToast({
        title: '请输入宝宝昵称',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      let score = +e.detail.value.score,
        time = new Date().getTime()
      if (isNaN(score)) score = 0
      db.collection('baby').add({
        data: {
          name: name,
          score: score,
          oid: '',
          password: '',
          deled: false,
          create_time: time
        },
        success: res => {
          let baby_id = res._id
          db.collection('user_baby').add({
            data: {
              baby_id: baby_id,
              deled: false,
              create_time: time
            },
            success: res => {
              wx.hideLoading()
              that.xTap()
              that.loadBaby()
              wx.showToast({
                title: '添加成功',
                icon: 'success'
              })
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({
                title: '添加失败',
                icon: 'none'
              })
            }
          })
          if (score != 0) {
            db.collection('logs').add({
              data: {
                baby_id: baby_id,
                content: '初始积分',
                score: score,
                deled: false,
                create_time: time
              }
            })
          }
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            title: '添加失败',
            icon: 'none'
          })
        }
      })
    }
  },
  bindSubmit: function (e) {
    let that = this,
      data = that.data,
      openid = data.openid,
      oid = e.detail.value.oid,
      password = e.detail.value.password
    if (oid.length == 0 || password.length == 0) {
      wx.showToast({
        title: '请输入宝宝ID、密码',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      db.collection('baby').where({
        oid: oid,
        password: password,
        deled: false
      }).get({
        success: res => {
          if (res.data.length > 0) {
            let baby = res.data[0],
              time = new Date().getTime()
            db.collection('user_baby').where({
              _openid: openid,
              baby_id: baby._id
            }).get({
              success: res => {
                if (res.data.length > 0) {
                  db.collection('user_baby').where({
                    _openid: openid,
                    baby_id: baby._id
                  }).update({
                    data: {
                      deled: false,
                      create_time: time
                    }
                  })
                  wx.hideLoading()
                  that.xTap()
                  that.loadBaby()
                  wx.showToast({
                    title: '绑定成功',
                    icon: 'success'
                  })
                } else {
                  db.collection('user_baby').add({
                    data: {
                      baby_id: baby._id,
                      deled: false,
                      create_time: time
                    },
                    success: res => {
                      wx.hideLoading()
                      that.xTap()
                      that.loadBaby()
                      wx.showToast({
                        title: '绑定成功',
                        icon: 'success'
                      })
                    },
                    fail: err => {
                      wx.hideLoading()
                      wx.showToast({
                        title: '绑定失败',
                        icon: 'none'
                      })
                    }
                  })
                }
              },
              fail: err => {
                wx.showToast({
                  title: '操作失败',
                  icon: 'none'
                })
              }
            })
          } else {
            wx.showToast({
              title: '没有找到宝宝',
              icon: 'none'
            })
          }
        },
        fail: err => {
          wx.showToast({
            title: '没有找到宝宝',
            icon: 'none'
          })
        }
      })
    }
  },
  userEditTap: function () {
    let that = this
    that.setData({
      showForm: 'user'
    })
  },
  userSubmit: function (e) {
    let that = this,
      data = that.data,
      openid = data.openid,
      user = data.user,
      name = e.detail.value.name
    if (name.length == 0) {
      wx.showToast({
        title: '请输入家长昵称',
        icon: 'none',
        duration: 1000
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      db.collection('users').doc(openid).set({
        data: {
          name: name
        },
        success: res => {
          wx.hideLoading()
          user.name = name
          that.setData({
            user: user
          })
          that.xTap()
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          })
        },
        fail: err => {
          console.log(err)
          wx.hideLoading()
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      })
    }
  },
  onShow: function () {
    let that = this,
      openid = wx.getStorageSync('openid') || ''
    if (openid.length == 0) {
      that.getOpenid()
    } else {
      that.setData({
        openid: openid,
        isLoading: false
      }, () => {
        that.loadBaby()
      })
      db.collection('users').doc(openid).get({
        success: res => {
          that.setData({
            user: res.data
          })
        }
      })
    }
  },
  onPullDownRefresh: function () {
    let that = this
    wx.stopPullDownRefresh()
    that.loadBaby()
  },
})